first() { //Return first element //Return null for empty case if (this.isEmpty()) return null return this.get(0) }
linearSearch(anElem) { //Return matching element //or null if no match let i = 0 while (i < this.size()) { let nextElem = this.get(i) if (nextElem.equals(anElem)) return nextElem i++ } return null }
first() { //Return first element //Return null for empty case if (this.isEmpty()) return null return this.get(0) }
last() { //Return last element //Return null for empty case if (this.isEmpty()) return null return this.get(this.size() - 1) }
linearSearch(anElem) { //Return matching element //or null if no match let i = 0 while (i < this.size()) { let nextElem = this.get(i) if (nextElem.equals(anElem)) return nextElem i++ } return null }
sum() { //Return matching element //or null if no match let i = 0 let sum = 0 while (i < this.size()) { let nextElem = this.get(i) sum += nextElem i += 3 } return sum }
nestedLoopSum() { //Compute sums in a nested loop let i = 0 let sum = 0 while (i < this.size()) { let j = 0 while (j < this.size()) { let nextElem = this.get(i) sum += nextElem j++ } i++ } return sum }
crazyLogSum() { //Compute sums during a logarithmic effort let i = this.size() - 1 let sum = 0 while (i > 0) { let nextElem = this.get(i) sum += nextElem i = i / 2 } return sum }
Outer loop at O(n) Inner operation at O(log n)
foo(anElem) {
return this.linearSearch(anElem);
}
linearSearch(anElem) { //Return matching element //or null if no match let i = 0 while (i < this.size()) { let nextElem = this.get(i) if (nextElem.equals(anElem)) return nextElem i++ } return null }
O(n) + O(1) + O(1)
O(n)
foo(anElem) { this.linearSearch(anElem); this.linearSearch(anElem); }
O(n) + O(n) = 2 * O(n)
2 * O(n) = O(n)
Given data structure "structure" Algorithm #1: O(1) Do a complex user interface (UI) operation that does not depend on structure size Assume UI takes about ten minutes to complete When done, return first element in "structure" Algorithm #2: O(n) Do Linear Search of "structure"